import random
import datetime
import math
import pytz
from pytz import timezone

from pylons import session

# Fidocard:
# 		BWT info(5 bit) + mobile(36 bit) + random(1 bit) + fixed bit(1,1 bit)

class Algorithm :
	def fidocardBWT(self, num) :
		tmp = list()
		for i in range(0, 19) :
			tmp.append([num, i])
			lst = num & 3
			num = (num >> 2) + (lst << 36)
		tmp.sort()
		loc = 0
		res = 0
		for i in range(0, 19) :
			res = (res << 2) + (tmp[i][0] & 3)
			if (tmp[i][1] == 0) : loc = i
		res = (res << 5) + loc
		return res
			
	def fidocardRevBWT(self, num) :
		loc = 18 - (num & 31)
		num >>= 5
		eStart = [-1, -1, -1, -1]
		eNext = list()
		eTo = list()
		for i in range(0, 19) :
			cur = (num >> (i << 1)) & 3
			eNext.append(eStart[cur])
			eTo.append(cur)
			eStart[cur] = i
		app = eTo
		app.sort()
		app.reverse()
		bwtNext = list()
		for i in range(0, 19) :
			cur = app[18 - i]
			bwtNext.append(eStart[cur])
			eStart[cur] = eNext[eStart[cur]]
		bwtNext.reverse()
		res = 0
		for i in range(0, 19) :
			res = (res << 2) + app[loc]
			loc = bwtNext[loc]
		return res

	def calcFidocardByMobile(self, mobile) :
		m = int(mobile)
		res = 2 + random.randint(0, 1)
		for i in range(0, 18) :
			res = (res << 2) + (m & 3)
			m /= 4
		return self.fidocardBWT(res)

	def calcMobileByFidocard(self, fidocard) :
		t = self.fidocardRevBWT(fidocard)
		res = 0
		for i in range(0, 18) :
			res = (res << 2) + (t & 3)
			t >>= 2
		return res
		
def datetimeToStr(date) :
	china = timezone('Asia/Shanghai')
	return timezone('America/Los_Angeles').localize(date).astimezone(china).strftime('%m-%d %H:%M')

def dateToStr(date) :
	china = timezone('Asia/Shanghai')
	return timezone('America/Los_Angeles').localize(date).astimezone(china).strftime('%Y-%m-%d')
	
def checkTimeScope(pageId, interval = 1) :
	pageId = 'page.' + pageId
	if (not pageId in session) : 
		session[pageId] = datetime.datetime.now()
		session.save()
		return True
	else :
		lastTime = session[pageId]
		session[pageId] = datetime.datetime.now()
		session.save()
		if ((datetime.datetime.now() - lastTime).seconds < interval) : return False
		else : return True
		
def sendMail(mailFrom, mailTo, subject, content) :
	import smtplib
	from email.mime.multipart import MIMEMultipart
	from email.mime.text import MIMEText

	msg = MIMEMultipart('alternative')
	msg['Subject'] = subject
	msg['From'] = mailFrom
	msg['To'] = mailTo
	MIME = MIMEText(content, 'plain', _charset = 'utf8')
	msg.attach(MIME)
	s = smtplib.SMTP('localhost')
	s.sendmail(mailFrom, mailTo, msg.as_string())
	s.quit()
	
def calcSchoolMapLocRanking(avgRating, topicCount, visitCount) :
	return avgRating / 5.0 + 1.0 - 1.0 / (math.log(topicCount + 1) + 1.0) + 1.0 - 1.0 / (math.log(visitCount / 100.0 + 1.0) + 1.0)
